package com.feiniu.api.datasource;

import com.feiniu.api.datasource.annotation.DataSourceAnnotation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

public class DataSourceInterceptor {
	private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceInterceptor.class);

	public void before(JoinPoint point) {
		LOGGER.info("******************DataSourceInterceptor -> before***************************");
		LOGGER.info(point.toString());
		Object target = point.getTarget();
		String method = point.getSignature().getName();

		Class<?>[] classz = target.getClass().getInterfaces();
		LOGGER.info(classz[0].getName());

		Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
		try {
			Method m = classz[0].getMethod(method, parameterTypes);
			LOGGER.info(m.getName());

			if (m != null && m.isAnnotationPresent(DataSourceAnnotation.class)) {
				DataSourceAnnotation data = m.getAnnotation(DataSourceAnnotation.class);
				LOGGER.info("dataSource -> " + data.value());

				DatabaseContextHolder.setCustomerType(data.value());
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		LOGGER.info("******************DataSourceInterceptor -> before***************************");
	}

}
